﻿/*
 * G711Encoder.cpp
 *
 *  Created on: 2016年8月24日
 *      Author: zhengboyuan
 */

#include "BasicType.h"
#include "G711Encoder.h"
#include "G711EncoderContext.h"
#include "Application.h"
#include "CLog.h"


static Application& app()
{
	return Application::instance();
}



/**
 * 初始化
 * @return 0 表示成功
 */
DLLEXPORT int g711_init()
{
	app().init();

	return 0;
}

/**
 * 反初始化
 * @return
 */
DLLEXPORT int g711_quit()
{
	app().quit();

	return 0;
}


DLLEXPORT int g711_open(g711_t* handle, int codec, int freq, int channels)
{
	CLog::info("g711_open codec:%d, freq:%d, channels: %d\n", codec, freq, channels);

	if (!handle)
	{
		return EINVAL;
	}

	if (codec != MCODEC_G711A && codec != MCODEC_G711U)
	{
		return EINVAL;
	}

	if (freq <= 0 || channels <= 0)
	{
		return EINVAL;
	}

	G711EncoderContextPtr encoder(new G711EncoderContext());

	int rc = encoder->open(codec, freq, channels);
	if (rc != 0)
	{
		return rc;
	}

	*handle = app().put(encoder);

	return 0;
}


/**
 * 关闭通道
 * @param handle 通道句柄
 */
DLLEXPORT void g711_close(g711_t handle)
{
	G711EncoderContextPtr encoder = app().remove(handle);
	if (encoder)
	{
		encoder->close();
	}
}

DLLEXPORT int g711_encode(g711_t handle, uint8_t* data, int length, int64_t pts, MPacket* pkt)
{
	//CLog::info("g711_encode handle:%d, length:%d, pts:%lld\n", handle, length, pts);
	if (!data || (length <= 0) || !pkt)
	{
		return EINVAL;
	}

	G711EncoderContextPtr encoder = app().get(handle);
	if (!encoder)
	{
		return EINVAL;
	}
	
	return encoder->encode(data, length, pts, pkt);
}